﻿using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


/// <summary>
/// UserBase 的摘要说明
/// </summary>
public class _rky : System.Web.UI.Page
{


    Entities db = new Entities();
    public _rky()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //    
    }



    //通过openid取得名字
    public static string getUnamebyOPID(string _OpenId)
    {
        Entities db = new Entities();
        string name = "";
        var _User = db.User.SingleOrDefault(p => p.UOpenID == _OpenId);
        if (_User != null)
        {
            name = string.IsNullOrEmpty(_User.UNickName) ? _User.UOpenID : _User.UNickName;
        }
        return name;
    }



    //通过openid取得名字
    public static string getUimgbyOPID(string _OpenId)
    {
        Entities db = new Entities();
        string name = "";
        var _User = db.User.SingleOrDefault(p => p.UOpenID == _OpenId);
        if (_User != null)
        {
            name = string.IsNullOrEmpty(_User.Utouxiang) ? _User.UHeadImg : _User.Utouxiang;      //"/upload/20200811/2020081116434705.png";//
        }
        return name;
    }

    //通过openid取得shangji名字
    public static string getUpByguid(string Uguid)
    {
        Entities db = new Entities();
        string name = "";
        var _User = db.User.SingleOrDefault(p => p.UGuid == Uguid);
        if (_User!= null)
        {


            name = getUwxandTElByguid(Convert.ToString(_User.UIndirectParentId));
           
        }
        return name;
    }

    public static string getUIDByGuid(string Uguid)
    {
        Entities db = new Entities();
        string name = "";
        var _User = db.User.SingleOrDefault(p => p.UGuid == Uguid);
        if (_User != null)
        {


            name = Convert.ToString(_User.UID);
        }
        return name;
    }

    



    //通过guid取得名字
    public static string getUnameByguid(string _Guid)
    {
        string name = "";
        if (_Guid == "8888")
        {
            name = "总部";
        }
        else
        { 
        Entities db = new Entities();
        var _User = db.User.SingleOrDefault(p => p.UGuid == _Guid);
        if (_User != null)
        {
            name = _User.UNickName;
        }
        }
        return name;
    }

    //通过guid取得opid
    public static string getOpenIDByguid(string _Guid)
    {
        Entities db = new Entities();
        string UOpenID = "";
        var _User = db.User.SingleOrDefault(p => p.UGuid == _Guid);
        if (_User != null)
        {
            UOpenID = _User.UOpenID;
        }
        return UOpenID;
    }


    //通过guid取得opid
    public static string getStateByguid(string _Guid)
    {
        Entities db = new Entities();
        string UOpenID = "";
        var _State = db.User.SingleOrDefault(p => p.UGuid == _Guid).Ustate;
        if (_State != null)
        {
            UOpenID = getUstat(_State.ToString());
        }
        return UOpenID;
    }



    public static string getTJnumberBYguid(string _Guid)
    {
        Entities db = new Entities();
         var   shareCount = db.User.Count(p => p.UIndirectParentId == _Guid).ToString();
        return shareCount;
    }




    public static decimal getCZbyopenid(string openid)//,商品ID
    {

        decimal mycz =0;
        using (Entities MyDB = new Entities())
        {

            mycz =Convert.ToDecimal(MyDB.U_CZ.Where(x => x.UGuid == openid).Where(x => x.CZstat == 1).Sum(x => x.CZMoney)); //充值 消费 提现
          
        }
        return mycz;
    }


    public static List<T> getSPnamebyID<T>(string spid)//,商品ID
    {

        List<T> mylist = new List<T>();
        using (Entities MyDB = new Entities())
        {
           
            var cz = MyDB.U_CZ.Where(x => x.UGuid == spid).Where(x => x.CZstat == 1).Sum(x => x.CZMoney); //充值 消费 提现
            if (cz == null) cz = 0;
        }
        return mylist;
    }




    //通过guid   gid  取可进货库存
    //进货库存
    public static int getJHkc(string _Guid, string SPID)
    {
        using (Entities MyDB = new Entities())
        {
            int _spid = int.Parse(SPID);
            int gkucunCount = 0;
            var gjhCount = Convert.ToInt32(MyDB.Y_Order.Where(x => x.UGUID == _Guid && x.OState == 0 && x.SPID == _spid).Sum(t => t.ONumber));
            var gchCount = Convert.ToInt32(MyDB.Y_Order.Where(x => x.UparentId == _Guid && x.OState == 0 && x.SPID == _spid).Sum(t => t.ONumber));
            var gthCount = Convert.ToInt32(MyDB.S_Order.Where(x => x.UGUID == _Guid && x.OState != -2 && x.SPID == _spid).Sum(t => t.ONumber));
            gkucunCount = gjhCount - gchCount - gthCount;

            return gkucunCount;
        }


    }


    //取得 各个上级总的库存
    public static int getGoodNU(int MYstat, string DirectPguid,string SPID)
    {
        var allp = new List<string>();
        var xx=getMyParens(allp, MYstat, DirectPguid);
        int myspKC = 0;
        if (xx != null)
        {
            foreach (var x in xx)
            {
                myspKC += getKCByguidGID(x,SPID);
            }

        }
        using (Entities db = new Entities())
        {
            int _spid = int.Parse(SPID);
            var cc = db.S_Goods.SingleOrDefault(x => x.GID == _spid);

            int yuding = Convert.ToInt32(db.Y_Order.Where(x => x.SPID == _spid && x.OState >= 0 && x.UparentId == "8888").Sum(t => t.ONumber));

            if (cc != null)
                myspKC +=(Int32)cc.GCounts- yuding;
        
        }

        if (myspKC < 0)
            myspKC = 0;

        return myspKC;
    }





    //循环出 所有上级的方法
    public static List<string> getMyParens(List<string> allp, int MYstat, string DirectPguid)
    {
        using (Entities db = new Entities())
        {
            var pUser = db.User.FirstOrDefault(p => p.UGuid == DirectPguid); //panduan 上级
            if (pUser == null)
              {
                //allp.Add("8888");
                return allp;
              }
            else                           //否则向上找
            {
                if (pUser.Ustate > MYstat)  //  如果上级大于我的
                {
                    allp.Add(pUser.UGuid);
                    return getMyParens(allp, (Int16)pUser.Ustate, pUser.UIndirectParentId);
                }
                else
                {
                    return getMyParens(allp, (Int16)pUser.Ustate, pUser.UIndirectParentId);
                }
            }
        }
    }


    //    public static int getparentKC(int statKC,int MYstat, string DirectPguid,int SPID)
    //{

    //    using (Entities db = new Entities())
    //    {
    //        var pUser = db.User.SingleOrDefault(p => p.UGuid == DirectPguid); //panduan 上级
    //        if (pUser == null)  //没有上级 直接找到厂家
    //        {
    //            var cc = db.S_Goods.SingleOrDefault(x => x.GID == SPID);
    //            if (cc != null)
    //                return (Int32)cc.GCounts;
    //            else
    //                return 0;
    //        }
    //        else                           //否则向上找
    //        {
    //            if (pUser.Ustate > MYstat) //如果 上级 的 级别大于 我
    //            {
    //                return pUser.UGuid;
    //            }
    //            else
    //            {
    //                return getparentKC(statKC, MYstat, pUser.UIndirectParentId,SPID);
    //            }
    //        }
    //    }

    //}



        //通过guid   gid  取库存
        public static int getKCByguidGID(string _Guid,string SPID)
    {
        using (Entities MyDB = new Entities())
        {
            int _spid = int.Parse(SPID);

            int gkucunCount = 0;
            var gjhCount = Convert.ToInt32(MyDB.Y_Order.Where(x => x.UGUID == _Guid && x.OState == 0 && x.SPID == _spid).Sum(t => t.ONumber));
            var gchCount = Convert.ToInt32(MyDB.Y_Order.Where(x => x.UparentId == _Guid && x.OState == 0 && x.SPID == _spid).Sum(t => t.ONumber));
            var gthCount = Convert.ToInt32(MyDB.S_Order.Where(x => x.UGUID == _Guid && x.OState>-1 && x.SPID == _spid).Sum(t => t.ONumber));
            gkucunCount =gjhCount - gchCount- gthCount;

            return gkucunCount;
        }

    
    }
 
    //通过guid    取总库存
    public static string getALLKCByguidGID(string _Guid)
    {
        using (Entities MyDB = new Entities())
        {
            int kucunCount = 0;
            var jhCount = Convert.ToInt32(MyDB.Y_Order.Where(x => x.UGUID == _Guid && x.OState == 0).Sum(t => t.ONumber));
            var chCount = Convert.ToInt32(MyDB.Y_Order.Where(x => x.UparentId == _Guid && x.OState == 0).Sum(t => t.ONumber));
            var thCount = Convert.ToInt32(MyDB.S_Order.Where(x => x.UGUID == _Guid && x.OState >-1).Sum(t => t.ONumber));
            kucunCount = jhCount - chCount- thCount;

            string result = kucunCount.ToString();
            return result;
        }
       
    }



    //通过guid求出  总业绩
    public static string getYJByGUID(string _Guid)//,商品ID,购买者OpenId
    {
        Entities db = new Entities();
        var Deyeji = Convert.ToDouble(db.Y_Order.Where(x => x.UGUID == _Guid && x.OState == 0).Sum(t => t.OLastPrice));
        return Deyeji.ToString();
    }


   



    public static string getJHparent(int MYstat, string DirectPguid)
    {
        using (Entities db = new Entities())
        {
            var pUser = db.User.SingleOrDefault(p => p.UGuid == DirectPguid); //panduan 上级
            if (pUser == null)
                return "8888";
            else                           //否则向上找
            {
                if (pUser.Ustate > MYstat)
                {
                    return pUser.UGuid;
                }
                else
                {
                    return getJHparent(MYstat, pUser.UIndirectParentId);
                }
            }
        }

    }


    //后台用 通过 guid取得联系信息
    public static string getUinfoByguid(string _Guid)
    {
        string name = "";
        if (_Guid != "")
        { 
        
       
        if (_Guid == "8888")
        {
            name = "总部";
        }
        else
        {
                using (Entities db = new Entities())
                { 
                    var _User = db.User.SingleOrDefault(p => p.UGuid == _Guid);
                        if (_User != null)
                        {
                            name = " <p>" + _User.UNickName + "</p><p>当时：" + getUstat(_User.Ustate.ToString()) + "</p><p>" + _User.Uwx + "</p><p>" + _User.UTel+"</p>";

                        }
                }
            }
        }
        else
        {
            name = "无";
        }
        return name;
    }


    public static string getUwxandTElByguid(string _Guid)
    {
        Entities db = new Entities();
        string name = "";
        if (_Guid == "8888")
        {
            name = "总部";
        }
        else
        {

            var _User = db.User.SingleOrDefault(p => p.UGuid == _Guid);
            if (_User != null)
            {
                name = "微信昵称：" + _User.UNickName + "\n微信号：" + _User.Uwx + "\n电话：" + _User.UTel;

            }
        }
        return name;
    }

    //取重
    public static string getWeight(string spid)
    {
        string Result = "";
        using (Entities MyDB = new Entities())
        {
            int intspid = int.Parse(spid);
            var Weight = MyDB.S_Goods.SingleOrDefault(x => x.GID == intspid).GWeight;
            if (Weight != null)
            {
                Result = Weight.ToString();
            }
        }
        return Result;
    }

    

    #region 获取第一张图片
    /// <summary>
    /// 获取第一张图片
    public static string getFirstImg(string spid)
    {
        string Result = "";
        using (Entities MyDB = new Entities())
        {
            int intspid = int.Parse(spid);
            var Img = MyDB.S_Goods.SingleOrDefault(x => x.GID == intspid).GImg;
            if (Img != null)
            {
                string[] imgArr = Img.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (imgArr.Length != 0)
                    Result = imgArr[0];
            }
        }
        return Result;
    }
    #endregion




    #region 获取第一张图片
    /// <summary>
    /// 获取第一张图片
    public static string getFirstImgByimg(string imgs)
    {
        string Result = "";

            if (imgs != null)
            {
                string[] imgArr = imgs.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (imgArr.Length != 0)
                    Result = imgArr[0];
            }
        return Result;
    }
    #endregion


    #region 获取第一张图片
    /// <summary>
    /// 获库存
    public static int getKCnumber(string spid)
    {
        int Result = 0;
        using (Entities MyDB = new Entities())
        {
            int intspid = int.Parse(spid);
            var Number = MyDB.S_Order.Where(x => x.SPID == intspid).Sum(x=>x.ONumber);
            if (Number != null)
            {
                    Result =Convert.ToInt32(Number);
            }
        }
        return Result;
    }
    #endregion
    #region 获取第一张图片
    /// <summary>
    /// 获取第一张图片
    public static string getMYprice(string spid,string leve)
    {
        string Result = "null";
        using (Entities MyDB = new Entities())
        {
            int intspid = int.Parse(spid);
            var good = MyDB.S_Goods.SingleOrDefault(x => x.GID == intspid);
            if(good != null)
            {
                switch (leve)
                {
                    case "0":
                        Result = good.GPrice.ToString();
                        break;
                    case "1":
                        Result = good.RpriceCJHY.ToString();//超级会员
                        break;
                    case "2":
                        Result = good.RpriceYJDL.ToString();//铂金会员
                        break;
                    case "3":
                        Result = good.RpriceZD.ToString();//二级经销商
                        break;
                    case "4":
                        Result = good.RpriceHHR.ToString();//一级经销商
                        break;
                    case "5":
                        Result = good.RpriceDS.ToString();//总经销商
                        break;
                    case "6":
                        Result = good.RpriceZXDS.ToString();//z总经销商
                        break;
                    default:
                        Result = good.GPrice.ToString();//顾客
                        break;
                }    
            }
        }
        return Result;
    }
    #endregion

    public static string getUstatByGUID(string _Guid)//,商品ID,购买者OpenId
    {
        Entities db = new Entities();
        string Result = "";
        var _User = db.User.SingleOrDefault(p => p.UGuid == _Guid);
        if (_User != null)
        {

            Result=getUstat(_User.Ustate.ToString());
        }
        return Result;
    }




   public static string getUstat(string Ustate)//,商品ID,购买者OpenId
    {
        string Result = "";
        switch (Ustate)
        {

            case "0":
                Result = "会员";
                break;
            case "1":
                Result = "推客";
                break;
            case "2":
                Result = "片区";
                break;
            case "3":
                Result = "大区";
                break;
         
            default:
                Result = "会员";
                break;
        }
        return Result;
    }


    //下面的方法会生成一个短的字符串，并且这个字符串是唯一的。重复1亿次都不会出现重复的，它也是依照GUID的唯一性来生成这个字符串的。
    public static string GenerateStringID()
    {
        long i = 1;
        foreach (byte b in Guid.NewGuid().ToByteArray())
        {
            i *= ((int)b + 1);
        }
        return string.Format("{0:x}", i - DateTime.Now.Ticks);
    }


    public static string getSordeSumMoney(string OrderId)
    {
        double Result = 0;
        int _OrderId = int.Parse(OrderId);
        Entities db = new Entities();
            var mnews = db.S_Order.Where(x => x.OParentId == _OrderId || x.OrderID == _OrderId);
            foreach (var m in mnews)
            {
                Result += Convert.ToDouble(m.SPrice * m.ONumber + m.OpostPrice);
            }



        return Result.ToString("0.00");

    }


        #region 获取订单总价
        public static double getSumMoney(string OrderId, string myfg, string jb)
    {
        double Result = 0;
        int _OrderId = int.Parse(OrderId);
        Entities db = new Entities();

        if (myfg.ToUpper() == "SS")//
        {
            var mnews = db.S_Order.Where(x => x.OParentId == _OrderId || x.OrderID == _OrderId);
            foreach (var m in mnews)
            {
                if (jb == "0")
                {
                    Result += Convert.ToDouble(m.STruePrice * m.ONumber+ m.OpostPrice);

                }
                else
                {
                    Result += Convert.ToDouble(m.OLastPrice+ m.OpostPrice);

                }
            }

        }
        if (myfg.ToUpper() == "DD")//
        {
            var mnews = db.S_DinDan.Where(x => x.OParentId == _OrderId || x.DingDdanID == _OrderId);
            foreach (var m in mnews)
            {
                if (jb == "0")
                {
                    Result += Convert.ToDouble(m.STruePrice * m.ONumber + m.OpostPrice);

                }
                else
                {
                    Result += Convert.ToDouble(m.OLastPrice + m.OpostPrice);

                }
            }

        }
        if (myfg.ToUpper() == "YS")//
        {
            var mnews = db.Y_Order.Where(x => x.OParentId == _OrderId || x.OrderID == _OrderId);
            foreach (var m in mnews)
            {
                if (jb == "0")
                {
                    Result += Convert.ToDouble(m.STruePrice * m.ONumber);

                }
                else if (jb == "1")
                {
                    Result += Convert.ToDouble(m.OLastPrice);

                }
                //else if (jb == "2")
                //{
                //    Result += Convert.ToDouble(m.OFinalPrice);
                //}
            }
        }

        if (myfg.ToUpper() == "PP")//
        {
                    var mnews = db.S_Order.FirstOrDefault(x => x.OrderID == _OrderId);
         
                    Result = Convert.ToDouble(mnews.OpostPrice); 
        }
        return Result;
    }
    #endregion


    /// 获取订单总重量
    public static double getSumWeight(string OrderId)
    {
        double Result = 0;
        int _OrderId = int.Parse(OrderId);
        using (Entities db = new Entities())
        {

            var mnews = db.S_Order.Where(x => x.OParentId == _OrderId || x.OrderID == _OrderId);
            foreach (var m in mnews)
            {

                Result += Convert.ToDouble(m.OALLweight);
            }

        }
        return Result;
    }


    #region Token

    //获得当前Session里保存的标志
    public static string GetToken()
    {
        if (null != HttpContext.Current.Session["Token"])
        {
            return HttpContext.Current.Session["Token"].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    //生成标志，并保存到Session
    public static void SetToken()
    {
        HttpContext.Current.Session.Add("Token", UserMd5(HttpContext.Current.Session.SessionID + DateTime.Now.Ticks.ToString()));
    }

    //这个函数纯粹是为了让标志稍微短点儿，一堆乱码还特有神秘感，另外，这个UserMd5函数是网上找来的现成儿的
    protected static string UserMd5(string str1)
    {
        string cl1 = str1;
        string pwd = "";
        MD5 md5 = MD5.Create();
        // 加密后是一个字节类型的数组
        byte[] s = md5.ComputeHash(Encoding.Unicode.GetBytes(cl1));
        // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
        for (int i = 0; i < s.Length; i++)
        {
            // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符
            pwd = pwd + s[i].ToString("X");
        }
        return pwd;
    }

    #endregion

    #region 返回小数点后2位，不四舍五入
    /// <summary>
    /// 返回小数点后2位，不四舍五入
    /// </summary>
    /// <param name="number"></param>
    /// <returns></returns>
    public static decimal Back2(decimal number)
    {
        return Math.Floor(number * 100) / 100;
    }
    #endregion

    /// <summary>
    /// 查积分
    /// </summary>
    /// <param name="openid"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    #region
    public static decimal getJF(string uguid, string type)
    {
        using (Entities db = new Entities())
        {
            var jfadd = Convert.ToDecimal(db.U_JF.Where(x => x.UGuid == uguid && x.JGetWay == "充值").Sum(x => x.JFen));
            var jforder = db.Y_Order.Where(x => x.UGUID == uguid && x.OPayState == 1 && x.OpayType == "jf").Sum(x => x.OLastPrice);

            if (jforder != null)
            {
                return Convert.ToDecimal(jfadd - jforder);
            }
            else
            {
                return Convert.ToDecimal(jfadd);
            }
        }
    }
    #endregion

    #region 时间戳反转为时间
    /// <summary>
    /// 时间戳反转为时间，有很多中翻转方法，但是，请不要使用过字符串（string）进行操作，大家都知道字符串会很慢！
    /// </summary>
    /// <param name="TimeStamp">时间戳</param>
    /// <param name="AccurateToMilliseconds">是否精确到毫秒</param>
    /// <returns>返回一个日期时间</returns>
    public static DateTime GetTime(long TimeStamp, bool AccurateToMilliseconds = false)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
        if (AccurateToMilliseconds)
        {
            return startTime.AddTicks(TimeStamp * 10000);
        }
        else
        {
            return startTime.AddTicks(TimeStamp * 10000000);
        }
    }
    #endregion



    /// <summary>
    /// 级别修改状态日志写入
    /// </summary>
    /// <param name="str"></param>
    public static void SaveUstatLogs(string UGuid, int Ustate, DateTime endTime, string logRen, string LogRenType)
    {
        Entities mydb = new Entities();
        {
            U_State_Log Lg = new U_State_Log();

            Lg.UGuid = UGuid;
            Lg.Ustate = Ustate;


            Lg.EndTime = endTime;
            Lg.logTime = DateTime.Now;

            Lg.logRen = logRen;
            Lg.LogRenType = LogRenType;

               Lg.logIP = GetIP();
            //Lg.logOX = GetIP();
            mydb.U_State_Log.Add(Lg);
            mydb.SaveChanges();

        }
    }


    /// <summary>
    /// 订单修改状态日志写入
    /// </summary>
    /// <param name="str"></param>
    public static void SaveOrderLogs(string OrderType, string OrderID, int Ostate,string COntent, string logRen, string LogRenType)
    {
        Entities mydb = new Entities();
        {
            Order_Log Lg = new Order_Log();


            Lg.OrderType = OrderType;
            Lg.OrderID = OrderID;
            Lg.Ostate = Ostate;
            Lg.logContent = COntent;
            Lg.logTime = DateTime.Now;
            Lg.logRen = logRen;
            Lg.LogRenType = LogRenType;

            Lg.logIP = GetIP();
            //Lg.logOX = GetIP();
            mydb.Order_Log.Add(Lg);
            mydb.SaveChanges();

        }
    }



    public static string GetIP()
    {
        string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        if (string.IsNullOrEmpty(result))
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (string.IsNullOrEmpty(result))
            result = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(result) || !IsIP(result))
            return "127.0.0.1";

        return result;
    }


    /// <summary>
    /// 是否为ip
    /// </summary>
    /// <param name="ip"></param>
    /// <returns></returns>
    public static bool IsIP(string ip)
    {
        return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }




}